import request from '@/utils/request'

const state = {
  cartItems: [],
  cartItemCount: 0
}

const mutations = {
  SET_CART_ITEMS: (state, items) => {
    state.cartItems = items
  },
  SET_CART_ITEM_COUNT: (state, count) => {
    state.cartItemCount = count
  }
}

const actions = {
  // 获取购物车列表
  async getCartItems({ commit }) {
    try {
      const response = await request({
        url: '/api/cart',
        method: 'get'
      })
      if (response.code === 200 && response.data) {
        const cartItems = response.data.map(item => ({
          ...item,
          productImage: item.productImage || '/uploads/products/default.jpg',
          totalPrice: (item.price * item.quantity).toFixed(2)
        }))
        commit('SET_CART_ITEMS', cartItems)
        commit('SET_CART_ITEM_COUNT', cartItems.reduce((total, item) => total + item.quantity, 0))
        return cartItems
      } else {
        throw new Error(response.message || '获取购物车失败')
      }
    } catch (error) {
      console.error('获取购物车失败:', error)
      throw error
    }
  },

  // 添加商品到购物车
  async addProductToCart({ dispatch }, { productId, quantity }) {
    try {
      const response = await request({
        url: '/api/cart',
        method: 'post',
        params: { productId, quantity }
      })
      if (response.code === 200) {
        // 添加成功后刷新购物车列表
        await dispatch('getCartItems')
        return true
      } else {
        throw new Error(response.message || '添加到购物车失败')
      }
    } catch (error) {
      console.error('添加到购物车失败:', error)
      throw error
    }
  },

  // 更新购物车商品数量
  async updateCartItemQuantity({ dispatch }, { id, quantity }) {
    try {
      await request({
        url: `/api/cart/${id}/quantity`,
        method: 'put',
        params: { quantity }
      })
      await dispatch('getCartItems')
    } catch (error) {
      throw error
    }
  },

  // 从购物车中移除商品
  async removeFromCart({ dispatch }, id) {
    try {
      await request({
        url: `/api/cart/${id}`,
        method: 'delete'
      })
      await dispatch('getCartItems')
    } catch (error) {
      throw error
    }
  },

  // 清空购物车
  async clearCart({ commit }) {
    try {
      await request({
        url: '/api/cart',
        method: 'delete'
      })
      commit('SET_CART_ITEMS', [])
      commit('SET_CART_ITEM_COUNT', 0)
    } catch (error) {
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 